// sm2_encrypt.c
#include <stdio.h>
#include <stdlib.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include "utils.h"

int main(int argc, char *argv[]) {
    if (argc != 4) {
        fprintf(stderr, "Usage: %s <input_file> <pubkey.pem> <output_file>\n", argv[0]);
        exit(1);
    }

    const char *in_file = argv[1];
    const char *pubkey_file = argv[2];
    const char *out_file = argv[3];

    size_t in_len;
    unsigned char *in_data = read_file(in_file, &in_len);

    FILE *fp = fopen(pubkey_file, "r");
    EVP_PKEY *pkey = PEM_read_PUBKEY(fp, NULL, NULL, NULL);
    fclose(fp);
    if (!pkey) {
        fprintf(stderr, "Failed to read public key\n");
        exit(1);
    }

    EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new(pkey, NULL);
    if (!ctx) goto err;

    if (EVP_PKEY_encrypt_init(ctx) <= 0 ||
        EVP_PKEY_CTX_set_ec_scheme(ctx, NID_sm2) <= 0) goto err;

    size_t out_len;
    if (EVP_PKEY_encrypt(ctx, NULL, &out_len, in_data, in_len) <= 0) goto err;

    unsigned char *out_data = malloc(out_len);
    if (!out_data) goto err;

    if (EVP_PKEY_encrypt(ctx, out_data, &out_len, in_data, in_len) <= 0) {
        free(out_data);
        goto err;
    }

    write_file(out_file, out_data, out_len);
    free(out_data);
    EVP_PKEY_CTX_free(ctx);
    EVP_PKEY_free(pkey);
    free(in_data);
    printf("SM2 encryption succeeded.\n");
    return 0;

err:
    fprintf(stderr, "SM2 encryption failed.\n");
    EVP_PKEY_CTX_free(ctx);
    EVP_PKEY_free(pkey);
    free(in_data);
    exit(1);
}
